//
//  ShopCommentsViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-8.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ShopCommentsViewController.h"
#import "PostCommentViewController.h"
#import "LoginViewController.h"
#import "ShopCommentsCell.h"

#define TOTAL_COMM_FORMAT_TEXT  @"共%@条点评"
#define TOTAL_POINT_FORMAT_TEXT @"饭友总体平均评分：%@分"

@interface ShopCommentsViewController ()

@end

@implementation ShopCommentsViewController


- (id)init
{
    self = [super initWithNibClass:[ShopCommentsViewController class]];
    if (self) {
        
    }
    return self;
}

- (id)initWithShopId:(NSString*)shopId
{
    self = [self init];
    if (self) {
        _shopId = shopId;
        _dataSource = [[ShopCommentsDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI
{
    [self createNavigation:@"用户点评"];
    [self createLeftButton];
    [self createRightButton:@"点评"];
    
    self.commentsTable.delegate = _dataSource;
    self.commentsTable.dataSource = _dataSource;
    self.commentsTable.height = ScreenHeight - NavBarHeight - StatusBarHeight - _topView.height - TabBarHeight;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_dataSource fetchCommentsIsLoadMore:NO];
}

- (void)leftButtonClick:(id)sender
{
    [self pushOrPopViewController:[ShopHomeViewController class]];
}

- (void)rightButtonClick:(id)sender
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    PostCommentViewController *postCommentsVC = [[PostCommentViewController alloc] initWithShopId:_shopId];
    postCommentsVC.parentController = self;
    [self.navigationController pushViewController:postCommentsVC animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)setViewsValue:(NSDictionary*)data
{
    NSString *commCount = [[data objectForKey:@"pinglunshu"] stringValue];
    NSString *totalPoint = [data objectForKey:@"zongfen"];
    self.totalCommentsLabel.text = [NSString stringWithFormat:TOTAL_COMM_FORMAT_TEXT,commCount];
    self.totalPointLabel.text = [NSString stringWithFormat:TOTAL_POINT_FORMAT_TEXT,totalPoint];
}

- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.commentsList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.commentsList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [_commentsTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    self.moreLoading = NO;
}

@end

//=========================================================================================
#pragma ===================数据源类实现======================================================
//=========================================================================================

@implementation ShopCommentsDataSource

#define ShopCommentsCellId  @"ShopCommentsCell"
#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        self.commentsList = [[NSMutableArray alloc] initWithCapacity:10];
        self.commentsCell = [_viewController createCellWithNib:ShopCommentsCellId];
    }
    return self;
}

- (void)fetchCommentsIsLoadMore:(BOOL)isLoadMore
{
    if (!isLoadMore) [SVProgressHUD show];
    
    self.pageNumber = isLoadMore ? self.pageNumber : 1;
    
    NSString *url = [NSString stringWithFormat:API_SHOP_COMMENTS,_viewController.shopId, self.pageNumber];
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    
    NSDictionary *dic = [request.responseData JSONValue];
    NSDictionary *data = [dic objectForKey:@"data"];
    NSMutableArray *commList = [data objectForKey:@"pinglun"];
    
    if (request.tag == FETCH_NEW_TAG) {
        self.commentsList = commList;
        [self.viewController.commentsTable reloadData];
        [self.viewController setViewsValue:data];
    }
    
    if (request.tag == FETCH_MORE_TAG) {
        [_viewController appendTableWith:commList];
    }
    
    [SVProgressHUD dismiss];
}

#pragma ===================加载tableview数据 Begin================================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_commentsCell setContent:[self.commentsList objectAtIndex:indexPath.row]];
    return _commentsCell.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"ShopCommentsCell";
    
    ShopCommentsCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    [cell setContent:[self.commentsList objectAtIndex:indexPath.row]];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _commentsList.count-1 && _commentsList.count > 5) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            [self fetchCommentsIsLoadMore:YES];
            self.viewController.moreLoading = YES;
        }
    }
}

@end
